import PropTypes from "prop-types"
import React, { memo, useEffect, useRef } from "react"
import { IndicatorWrapper } from "./style"

const Indicator = memo((props) => {
    const { selectIndex } = props
    const contentRef = useRef()

    useEffect(() => {
        // 获取selectIndex滚动的距离 当前选中的.offsetLeft + 当前选中的.width * 0.5 - 容器.width *0.5
        const selectItemEl = contentRef.current.children[selectIndex]
        const itemElOffsetLeft = selectItemEl.offsetLeft
        const itemWidth = selectItemEl.clientWidth
        // 2.content的宽度
        const contentWidth = contentRef.current.clientWidth
        const contentScroll = contentRef.current.scrollWidth
        // 3.获取selectIndex 要滚动的距离
        let distance = `
            ${itemElOffsetLeft + itemWidth * 0.5 - contentWidth * 0.5}
        `
        // 4.特殊情况处理
        if (distance < 0) distance = 0 // 左边特殊情况处理
        // 总共可以滚动的距离
        const totalDistance = contentScroll - contentWidth 
        if (distance > totalDistance) distance = totalDistance // 右边特殊情况处理
        // 5.改变位置
        contentRef.current.style.transform = `translate(${-distance}px)`
    }, [selectIndex])

    return (
        <IndicatorWrapper>
            <div className="i-content" ref={contentRef}>
                {props.children}
            </div>
        </IndicatorWrapper>
    )
})

Indicator.propTypes = {
    selectIndex: PropTypes.number,
}

export default Indicator
